use std::cell::RefCell;
use std::fs::read_dir;
use std::rc::Rc;
use crate::model::file_node::FileNode;



pub fn scan_dir(dir: &str) -> std::io::Result<Rc<RefCell<FileNode>>> {
    let mut root = Rc::new(RefCell::new(FileNode {
        filename: dir.to_string(),
        size: 0,
        children: Vec::new(),
        parent: None,
    }));

    let mut files = Vec::new();
    files.push(root.clone());
    san_dir(&mut files)?;
    println!("获取到文件条数：{}", files.len());
    Ok(root)
}


fn san_dir(files: &mut Vec<Rc<RefCell<FileNode>>>) -> std::io::Result<()> {
    while let Some(file) = files.pop() {
        let result = read_dir(file.borrow().clone().get_path());

        if result.is_err() {
            println!("出现错误了");
            continue;
        }

        result?.for_each(|f| {
            match f {
                Ok(path) => {
                    let file_node = Rc::new(RefCell::new(FileNode {
                        filename: path.file_name().to_str().unwrap().to_string(),
                        size: 0,
                        children: Vec::new(),
                        parent: Some(file.clone()),
                    }));

                    file.borrow_mut().children.push(file_node.clone());

                    if path.file_type().unwrap().is_dir() {
                        // println!("{:?}", path.path().display().to_string());
                        files.push(file_node);
                    } else {
                    }
                }
                Err(e) => {
                    println!("{:?}", e);
                }
            }
        });
    }
    Ok(())
}

